package com.easipass.exangeservice.utils;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.ByteOrderMarkDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.charset.Charset;

/**
 * 
 * @version $Id$
 * @author itea
 * @date 2010-2-5
 */
public class EncodingDetector {

	static CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
	
	static {
		// Add the implementations of info.monitorenter.cpdetector.io.ICodepageDetector: 
	    // This one is quick if we deal with unicode codepages: 
	    detector.add(new ByteOrderMarkDetector()); 
	    // The first instance delegated to tries to detect the meta charset attribut in html pages.
	    detector.add(new ParsingDetector(true)); // be verbose about parsing.
	    // This one does the tricks of exclusion and frequency detection, if first implementation is 
	    // unsuccessful:
	    detector.add(JChardetFacade.getInstance()); // Another singleton.
	    detector.add(ASCIIDetector.getInstance()); // Fallback, see javadoc.
	}
	
	public static Charset getCharset(InputStream in, int len) throws IllegalArgumentException, IOException {
		return detector.detectCodepage(in, len);
	}
	
	public static Charset getCharset(File file) throws MalformedURLException, IOException {
		return detector.detectCodepage(file.toURI().toURL());
	}
}
